import express from 'express'
import multer from 'multer'
import path from 'path'
import fs from 'fs'
import iconv from 'iconv-lite'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)

const router = express.Router()
// 设置文件存储路径和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const folder = req.body.folder || 'bilibil'
    // 修改为与应用目录同级的 uploads 目录
    const uploadDir = path.resolve(process.cwd(), 'uploads', folder)
    console.log("path",uploadDir);
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true })
    }
    cb(null, uploadDir)
  },
  filename: function (req, file, cb) {
    
    // 获取当前年月日时分秒
    const now = new Date();
    const pad = n => n.toString().padStart(2, '0');
    const year = now.getFullYear();
    const month = pad(now.getMonth() + 1);
    const day = pad(now.getDate());
    const hour = pad(now.getHours());
    const minute = pad(now.getMinutes());
    const second = pad(now.getSeconds());
    const filename = iconv.decode(file.originalname,'utf-8'); 
    // 新文件名：yyyy-mm-dd_HH-MM-SS_原文件名
    const newName = `${year}-${month}-${day}_${hour}-${minute}-${second}_${filename}`;
    cb(null, newName);
  }
})

const upload = multer({ storage })

// 上传 Excel 文件接口
router.post('/uploadExcel', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '未上传文件' })
  }
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  res.json({
    message: '上传成功',
    filename: encodeURIComponent(req.file.filename),
    path: encodeURIComponent(req.file.path)
  })
})


router.post('/douyinUploadExcel', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '未上传文件' })
  }
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  res.json({
    message: '上传成功',
    filename: encodeURIComponent(req.file.filename),
    path: encodeURIComponent(req.file.path)
  })
})

export default router
